package com.vegetable.modules.service.stock.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.constant.CommonConstant;
import com.vegetable.modules.entity.inbound.AgentDeliveryDetailPack;
import com.vegetable.modules.entity.outbound.vo.SalesOutStatisticsVO;
import com.vegetable.modules.entity.stock.Stock;
import com.vegetable.modules.entity.stock.to.PriceElementChangeQueryTO;
import com.vegetable.modules.entity.stock.to.PriceElementDetailQueryTO;
import com.vegetable.modules.entity.stock.to.PriceTrendQueryTO;
import com.vegetable.modules.mapper.stock.StockMapper;
import com.vegetable.modules.service.inbound.IAgentDeliveryDetailPackService;
import com.vegetable.modules.service.stock.IPriceElementChangeService;
import com.vegetable.modules.vo.PriceElementChangeVO;
import com.vegetable.modules.vo.PriceElementDetailVO;
import com.vegetable.modules.vo.PriceTrendVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 价格要素变动服务实现类
 * </p>
 *
 * @author Qwen
 * @since 2025-09-27
 */
@Slf4j
@Service
public class PriceElementChangeServiceImpl extends ServiceImpl<StockMapper, Stock> implements IPriceElementChangeService {

    @Resource
    private StockMapper stockMapper;
    @Autowired
    private IAgentDeliveryDetailPackService iAgentDeliveryDetailPackService;

    @Override
    public IPage<PriceElementChangeVO> queryPriceElementChanges(PriceElementChangeQueryTO queryTO) {
        // 创建分页对象
        IPage<PriceElementChangeVO> page = new Page<>(queryTO.getPage(), queryTO.getLimit());

        // 查询数据
        return stockMapper.queryPriceElementChanges(page, queryTO);
    }

    
    /**
     * 查询价格要素详细记录
     * @param queryTO 查询条件
     * @return 价格要素详细记录列表
     */
    public List<PriceElementDetailVO> listPriceElementDetails(PriceElementDetailQueryTO queryTO) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("po", queryTO);
        
        // 查询数据
        List<PriceElementDetailVO> result = stockMapper.queryPriceElementDetails(queryTO);
        for(PriceElementDetailVO vo : result){
            if (!"小包装".equals(vo.getCategory()) ) {
                continue;
            }
            List<AgentDeliveryDetailPack> gMaterial = new ArrayList<>();
            List<AgentDeliveryDetailPack> pMaterial = new ArrayList<>();
            String packageCostStr = vo.getPackageCost();
            List<AgentDeliveryDetailPack> materialList;
            if(vo.getStockBatchNo().startsWith(CommonConstant.JGDB)){
                materialList = JSONArray.parseArray(packageCostStr, AgentDeliveryDetailPack.class);
            }else{
                materialList = iAgentDeliveryDetailPackService.selectByDetailId(vo.getStockDetailId());
            }
            if(CollectionUtil.isNotEmpty(materialList)){
                // 如果商品是小包装，所有包装归属于包装成本
                pMaterial = materialList;
            }
            Double packageCostWeight = pMaterial.stream().mapToDouble(flow -> NumberUtil.mul(flow.getUnitPrice(), flow.getStandardNumber()).doubleValue()).sum();
            // 蔬菜成本
            BigDecimal costForSales = vo.getCostWeight();
            // 包装成本
            BigDecimal packageForSales = new BigDecimal(packageCostWeight);
            // 小包装不再单独计算包装成本，而是把包装成本合计到蔬菜成本里
            costForSales = NumberUtil.add(costForSales, NumberUtil.div(packageCostWeight, vo.getStandard()));
            packageForSales = BigDecimal.ZERO;

            vo.setPackageUnitPrice(packageForSales);
            vo.setCostWeight(costForSales);
        }
        return result;
    }
    
    /**
     * 查询价格趋势
     * @param queryTO 查询条件
     * @return 价格趋势列表
     */
    public List<PriceTrendVO> listPriceTrend(PriceTrendQueryTO queryTO) {
        
        // 查询数据
        return stockMapper.queryPriceTrend(queryTO);
    }
    
    /**
     * 获取入库类型描述
     */
    public String getStorageTypeDescription(Integer storageType) {
        if (storageType == null) {
            return "";
        }
        
        switch (storageType) {
            case 0:
                return "代办交货";
            case 1:
                return "物流园";
            case 2:
                return "散货采购";
            default:
                return "其他";
        }
    }
}